package com.chenxinzhimusic.viewmodel


import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.chenxinzhimusic.api.Api
import com.chenxinzhimusic.entity.SuggestionItem
import com.chenxinzhimusic.util.page.AbsPagingSource
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest

class MusicSearchViewModel : ViewModel() {
    var searchContent by mutableStateOf("")
    var searchContentAction by mutableStateOf("")
    var searchTipList by mutableStateOf<List<SuggestionItem>>(listOf())
    @OptIn(ExperimentalCoroutinesApi::class)
    var searchList = snapshotFlow {
        searchContentAction
    }.distinctUntilChanged().flatMapLatest { query ->
        Pager(
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = false,
                prefetchDistance = 5
            ),
            pagingSourceFactory = {
                // 在这里传入 searchQuery 参数给 PagingSource 的构造函数
                AbsPagingSource(api = Api, query)
            }
        ).flow
    }
        .cachedIn(viewModelScope)



}
